import { StyleSheet, Text, View, Image, TouchableWithoutFeedback } from 'react-native'
import React, { useState, useMemo, useEffect } from 'react'
import Tabs from '../components/Tabs/Tabs'
import { connect } from 'react-redux'
import FlatList from '../components/FlatList'
import axios from '../axios'
import { getDomain } from '../utils/tools'
import { Button } from 'native-base'

const MyGoods = ({ navigation, goodsState }) => {
  // console.log('goodsState', goodsState)
  const tabs = useMemo(() => {
    const keys = Object.keys(goodsState)
    let tabs = keys.slice(0, keys.length / 2).map(state => {
      return {
        id: state,
        name: goodsState[state]
      }
    })
    return tabs
  }, [goodsState])
  const [current, setCurrent] = useState(0)
  const [status, setStatus] = useState('loading')
  const [query, setQuery] = useState({
    index: 1,
    size: 5,
    state: tabs[current].id
  })
  const [list, setList] = useState([])
  const [refreshing, setRefreshing] = useState(false)

  const onChange = (index) => {
    setStatus('loading')
    setCurrent(index)
    console.log(query)
    setList([])
    setQuery({
      ...query,
      index: 1,
      state: tabs[index].id
    })
  }
  const to = (id) => {
    navigation.navigate('GoodsDetail', {
      id
    })
  }

  const onEndReached = () => {
    if (status === 'noMore') return
    setStatus('loading')
    setQuery({
      ...query,
      index: query.index + 1
    })
  }
  const onRefresh = () => {
    setList([])
    setQuery({
      ...query,
      index: 1
    })
    setRefreshing(true)
  }
  const eidt = (id) => {
    navigation.navigate('UploadGoods', {
      id
    })
  }
  const puase = (id) => {
    axios.put('/goods', {
      id,
      state: goodsState.suspensive
    }).then(() => {
      setList([])
      setQuery({
        ...query,
        index: 1
      })
    })
  }
  const start = (id) => {
    axios.put('/goods', {
      id,
      state: goodsState.pending
    }).then(() => {
      setList([])
      setQuery({
        ...query,
        index: 1
      })
    })
  }
  const del = (id) => {
    axios.delete('/goods', {
      id
    }).then(() => {
      setList([])
      setQuery({
        ...query,
        index: 1
      })
    })
  }
  useEffect(() => {
    axios.get('/goods', query).then(res => {
      setList([...list, ...res.data.records])
      if (res.data.records.length < query.size) setStatus('noMore')
      else setStatus('more')
      setRefreshing(false)
    }).catch(err => {
      setRefreshing(false)
    })
  }, [query])
  const renderItem = ({ data }) => {
    return (
      <TouchableWithoutFeedback onPress={() => to(data._id)}>
        <View style={styles.card}>
          <View style={styles.body}>
            <Image style={styles.cover} source={{ uri: getDomain(data.pictures[0].url) }}></Image>
            <View style={styles.info}>
              <Text style={styles.title}>{data.title}</Text>
              <Text style={styles.price}>￥{data.price}</Text>
            </View>
          </View>
          <View style={styles.date}>
            <Text>创建时间：</Text>
            <Text>{data.createTime}</Text>
          </View>
          <View style={styles.handler}>
            {
              ![goodsState.overdue, goodsState.pending].includes(data.state) &&
              <Button style={styles.btn} size='sm' onPress={()=>eidt(data._id)}>编辑</Button>
            }
            {
              data.state === goodsState.suspensive &&
              <Button style={styles.btn} size='sm' onPress={()=>start(data._id)}>上架</Button>
            }
            {
              data.state === goodsState.published &&
              <Button style={styles.btn} size='sm' onPress={()=>puase(data._id)}>下架</Button>
            }
            <Button style={styles.btn} colorScheme='red' size='sm'
              onPress={()=>del(data._id)}
            >删除</Button>
          </View>
        </View>
      </TouchableWithoutFeedback>
    )
  }
  return (
    <View style={{ flex: 1 }}>
      <Tabs current={current} list={tabs} onChange={onChange}></Tabs>
      <FlatList data={list} renderItem={renderItem} status={status}
        onEndReached={onEndReached} onRefresh={onRefresh} refreshing={refreshing}></FlatList>
    </View>
  )
}

export default connect((state) => {
  console.log(state)
  return {
    goodsState: state.state.goodsState
  }
})(MyGoods)

const styles = StyleSheet.create({
  card: {
    backgroundColor: '#fff',
    marginBottom: 10,
    paddingHorizontal: 5,
    paddingVertical: 5
  },
  body: {
    display: 'flex',
    flexDirection: 'row'
  },
  info: {
    display: 'flex',
    justifyContent: 'space-between',
    paddingVertical: 2,
    paddingHorizontal: 5
  },
  price: {
    fontSize: 18
  },
  cover: {
    width: 100,
    height: 100
  },
  handler: {
    display: 'flex',
    flexDirection: 'row'
  },
  date: {
    display: 'flex',
    flexDirection: 'row',
    marginVertical: 5,
    color: '#999'
  },
  btn: {
    marginRight: 10
  }
})